package com.example.friendcash.utils.collections;

import com.android.internal.util.Predicate;
import com.example.friendcash.utils.functions.IIn;
import com.example.friendcash.utils.functions.IInt1In2;

import java.util.Iterator;

public class Sequences {

    /**
     * Iterates over the given sequence and invokes a callback for every item.
     *
     * @param sequence Sequence to be iterated over.
     * @param functor  A function to handle the value obtained from the iterator.
     * @param <T>      The type of both sequence and callback argument.
     * @return The same input sequence.
     */
    public static <T, I extends Iterable<T>> I each(I sequence, IIn<T> functor) {
        for (final T item : sequence) {
            functor.in(item);
        }
        return sequence;
    }

    public static <T, I extends Iterable<T>> I each(I sequence, IInt1In2<T> functor) {
        int i = 0;
        for (final T item : sequence) {
            functor.in(i++, item);
        }
        return sequence;
    }

    public static <T> void removeIf(Iterable<? extends T> sequence, Predicate<T> predicate) {
        final Iterator<? extends T> iterator = sequence.iterator();
        while ( iterator.hasNext() ) {
            if ( predicate.apply(iterator.next()) ) {
                iterator.remove();
            }
        }
    }


}
